# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : test.py
# Time       ：2024/5/30 16:29
# Author     ：huchl
# version    ：python 3.6
# Description：
"""
import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt

# 生成数据
x = np.random.rand(100, 1)
y = 2 + 3 * x + np.random.randn(100, 1)

# 分割数据集为训练集和测试集
x_train, x_test = x[:80], x[80:]
y_train, y_test = y[:80], y[80:]

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(units=1, input_shape=[1])
])

model.compile(optimizer='sgd', loss='mse')

history = model.fit(x_train, y_train, epochs=100, verbose=0)

loss = model.evaluate(x_test, y_test, verbose=0)
print(f'Test loss: {loss}')

predictions = model.predict(x_test)

plt.scatter(x_test, y_test, label='Actual')
plt.plot(x_test, predictions, color='red', linewidth=3, label='Predicted')
plt.legend()
plt.show()